<?php

class Admin_PostController extends Zend_Controller_Action
{

    public function init()
    {
        $this->view->sidebarMenu = 'post';
        $this->postModel = new Nosql_Model_Mysql_Post();
        $this->view->userObj = Zend_Auth::getInstance()->getIdentity();
    }

    public function indexAction()
    {
        $page = $this->_getParam('page');
        $page = (isset($page)) ? $page : 1;

        if (!Nosql_Util_Validator::validateInt($page)) {
            throw new Exception('Valor invalido en los parametros');
        }

        
        $posts = $this->postModel->listPosts($page);
        
        $this->view->posts = $posts['items'];
        if (count($this->view->posts) == 0) {
            $this->view->attention = array('No se encontraron artículos');
        } else {
            $this->view->paginator = $posts['paginator'];
            $this->view->urlPagination = '/admin/post/index/';
        }
        
    }

    public function addAction()
    {
        $form = new Admin_Form_Post();
        $form = $form->addPost();
        $errors = array();

        //Validate the form
        $request = $this->getRequest();
        if ($request->isPost()) {

            //valiate if theh form is valid
            if ( $form->isValid($request->getPost()) ) {

                $formValues = $form->getValues();

                // if there are no errors then I can create the user
                if (count($errors) == 0) {

                    $data['title'] = $formValues['post']['title'];
                    $data['category'] = $formValues['post']['category'];
                    $data['tags'] = $formValues['post']['tags'];
                    $data['content'] = $formValues['post']['content'];
                    $data['userid'] = $this->view->userObj->userid;

                    $response = $this->postModel->createPost($data);
                    if ($response['status'] > -1) {
                        $this->view->success = array("Artículo creado");
                        $this->_forward('index');
                        return;
                    } else {
                        $errors[] = $response['message'];
                    }
                }
            }
        }

        if (count($errors) > 0) {
            $this->view->errors = $errors;
        }

        $this->view->form = $form;
    }

    public function editAction()
    {
        $form = new Admin_Form_Post();
        $errors = array();
        $continue = true;

        //Validate the form
        $request = $this->getRequest();

        //get the User Object
        $id = $request->getParam('post');
        if ($id == null || !is_numeric($id)) {
            $continue = false;
            $errors[] = "No selecciono ningun artículo";
        }

        $post = null;
        if ($continue) {
            $post = $this->postModel->getPostById($id);
            if (!$post) {
                $continue = false;
                $errors[] = 'Hubo un error al obtener el artículo';
            } else {
                $form = $form->editPost($post['postid']);
            }
        }

        if ($continue && $request->isPost()) {
            //valiate if theh form is valid
            if ($form->isValid($request->getPost())) {

                $formValues = $form->getValues();

                // if there are no errors then I can create the user
                if (count($errors) == 0) {

                    $data['postid'] = $post['postid'];
                    $data['title'] = $formValues['post']['title'];
                    $data['category'] = $formValues['post']['category'];
                    $data['tags'] = $formValues['post']['tags'];
                    $data['content'] = $formValues['post']['content'];
                    $data['userid'] = $this->view->userObj->userid;

                    $response = $this->postModel->updatePost($data);
                    if ($response['status'] > -1) {
                        $this->view->success = array("Artículo actualizado exitosamente");
                        $this->_forward('index');
                        return;
                    } else {
                        $errors[] = $response['message'];
                    }
                }
            }
        }

        if (count($errors) > 0) {
            $this->view->errors = $errors;
        }

        if ($continue) {

            //Populate the Form
            $data['title'] = $post['title'];
            $data['category'] = $post['categoryid'];
            $data['content'] = $post['content'];
            if (isset($post['tags'])){
                $data['tags'] = Nosql_Util_Post::formatTagsArray($post['tags']);
            }

            $form->populate($data);
            $this->view->form = $form;
        }

        if (!$continue) {
            $this->_forward('index');
        }

        

    }

    public function deleteAction()
    {
        $success = array();
        $errors = array();
        $id = $this->getRequest()->getParam('post');
        if ($id == null || !is_numeric($id)) {
            $errors = array("No selecciono ningun artículo");
        } else {
            $response = $this->postModel->deletePostById($id);
            if ($response['status'] > 0) {

                $success[] = $response['message'];
            } else {
                $errors[] = $response['message'];
            }
        }

        if (count($errors) > 0) {
            $this->view->errors = $errors;
        }
        if (count($success) > 0) {
            $this->view->success = $success;
        }

        $this->_forward('index');
        return;
    }

    public function searchAction()
    {
        $form = new Admin_Form_Post();
        $errors = array();
        $success = array();
        $information = array();
        $continue = true;

        $page = $this->_getParam('page');
        $page = (isset($page)) ? $page : 1;

        if (!Nosql_Util_Validator::validateInt($page)) {
            throw new Exception('Valor invalido en los parametros');
        }


        $form = $form->searchPost();
        $request = $this->getRequest();
        if ($continue && $form->isValid($request->getParams())) {
            $formValues = $form->getValues();
            $query = $formValues['post']['q'];
            $field = $formValues['post']['field'];

            // NOW PREPARE THE VALUES TO DO THE SEARCH
            $useLiteral = false;
            switch ($field) {
                case 1:
                    $field = 'title';
                    break;
                case 2:
                    $field = 'categoryname';
                    break;
                case 3:
                    $field = 'tags';
                    break;
                case 4:
                    $field = 'content';
                    break;
                case 5:
                    $field = 'categoryid';
                    break;
                default:
                    $field = '';
                    break;
            }

            if (strlen($query) > 0 && strlen($field)>0 ) {
                if ($field == 'tags'){
                    $posts = $this->postModel->searchPostsByTag($query, $page);
                }else{
                    $posts = $this->postModel->searchPostsByField($query, $field, $page);
                }
                if ($posts['items']) {
                    $this->view->posts = $posts['items'];
                    $this->view->paginator = $posts['paginator'];
                    $this->view->urlPagination = '/admin/post/search/q/' . $query . '/field/' . $formValues['post']['field'] . '/';
                } else {
                    $information[] = 'Artículos no encontradas';
                }
            } else {
                $errors[] = 'Campo seleccionado es invalido';
            }
        }


        if (count($errors) > 0) {
            $this->view->errors = $errors;
        }
        if (count($success) > 0) {
            $this->view->success = $success;
        }
        if (count($information) > 0) {
            $this->view->information = $information;
        }
        $this->view->form = $form;
    }


}









